//
//  UserAccount.swift
//  Weibo
//
//  Created by 5201-mac on 2017/4/18.
//  Copyright © 2017年 wlb-mac. All rights reserved.
//

import UIKit

//自定义对象的归档和解归档必须遵守NSCoding协议，实现对应的方法

class UserAccount: NSObject, NSCoding {
    var access_token: String?
    var expires_in = 0
    var uid: String?
    
    init(dict: [String: NSObject]) {
        super.init()
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {

    }
    
    //通过归档的方式保存对象
    func saveAccount() {
        //将自定义对象存储到沙盒路径
        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    //获取自定义对象
    class func loadAccount() -> UserAccount? {
        //第一次没有存，会获取一个nil
        //解归档
        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")
        let account = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? UserAccount
        //print(account)
        return account
    }
    
    //实现归档和解归档的必选的协议方法
    
    //归档的方法，将自定义对象存储到沙盒中（二进制数据）
    func encode(with aCoder: NSCoder) {
        //将对象的属性进行存储
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_in, forKey: "expires_in")
        aCoder.encode(uid, forKey: "uid")
    }
    
    //解归档,将磁盘中的二进制数据解归档成自定义对象
    required init?(coder aDecoder: NSCoder) {
        //将当前对象的属性完成赋值
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expires_in = aDecoder.decodeInteger(forKey: "expires_in")
        uid = aDecoder.decodeObject(forKey: "uid") as? String
        
    }
}
